package com.yc.UI;

import java.util.List;
import java.util.Map;
import java.util.Random;


import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wb.swt.SWTResourceManager;

import com.yc.dao.ContactsDao;
import com.yc.dao.TrainDao;
import com.yc.dao.UserDao;
import com.yc.utils.SWTUtil;
import com.yc.utils.Values;

import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

/**
 *
 * @author UNO
 * 2021年7月1日下午2:59:53
 */
public class BuyingTicket {

	protected Shell shell;
	private boolean down = false;
	private int clickX = 0;
	private int clickY = 0;
	private Table table;
	private Table table_1;
	private String date = TicketingUI.date;//用户选择的出行日期
	public String str;  //选择性加0 之后的时间

	protected Map<String, Object> map = TicketingUI.amap;	//用户选择的列车的基本信息  列车表
	private String cname = map.get("c_name").toString();//用户选择的列车的名字

	TrainDao trainDao = new TrainDao();
	//列车票数和票价   票价表
	private Map<String, Object> map1 = trainDao.findPrice(cname, date);  //列车票数和票价   票价表

	ContactsDao ctd = new ContactsDao();
	String account = Values.currentLoginUser.get("u_name").toString();//当起用户的姓名
	List<Map<String, String>> list = ctd.findTRname(account);  //存的是该用户所有联系人的所有信息
	private String[] params = new String[list.size() + 1]; //用户的联系人们
	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			BuyingTicket window = new BuyingTicket();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell(SWT.NONE);
		shell.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		shell.setImage(SWTResourceManager.getImage(WelcomeUI.class, "/images/福字.png"));	
		shell.setSize(905, 507);
		shell.setText("SWT Application");
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));

		findContacts();  //在params中传入当前用户的联系人名字

		Composite composite = new Composite(shell, SWT.NONE);
		composite.setBackgroundMode(SWT.INHERIT_FORCE);
		//背景图片
		composite.setBackgroundImage(SWTResourceManager.getImage(WelcomeUI.class, "/images/back.jpg"));
		// 设置窗口居中
		SWTUtil.centerWindom(shell);


		//设置图标
		Label label_Icon = new Label(composite, SWT.NONE);
		label_Icon.setBounds(0, 0, 40, 40);
		label_Icon.setImage(SWTResourceManager.getImage(WelcomeUI.class,"/images/福字.png"));

		//关闭按钮
		Label label_close = new Label(composite, SWT.NONE);

		label_close.setBounds(863, 0, 40, 40);
		label_close.setImage(SWTResourceManager.getImage(WelcomeUI.class,"/images/关闭.png"));

		//最小化按钮
		Label label_min = new Label(composite, SWT.NONE);
		label_min.setBounds(817, 0, 40, 40);
		label_min.setImage(SWTResourceManager.getImage(WelcomeUI.class,"/images/最小化.png"));

		Label Label_title = new Label(composite, SWT.CENTER);
		Label_title.setText("确认购票");
		Label_title.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 14, SWT.NORMAL));
		Label_title.setBounds(46, 10, 107, 30);

		Combo combo_name = new Combo(composite, SWT.NONE);		
		combo_name.setBounds(128, 352, 92, 28);				
		combo_name.setItems(params);
		combo_name.setText(Values.currentLoginUser.get("u_name").toString());

		Label label = new Label(composite, SWT.CENTER);
		label.setText("乘车人：");
		label.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label.setBounds(0, 350, 107, 30);

		Button Bt_buyTicket = new Button(composite, SWT.NONE);

		Bt_buyTicket.setText("购票并支付");
		Bt_buyTicket.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 14, SWT.NORMAL));
		Bt_buyTicket.setBounds(402, 455, 122, 40);

		Combo combo_seat = new Combo(composite, SWT.NONE);

		combo_seat.setItems(new String[] {"硬座", "软卧", "硬卧", "无座"});
		combo_seat.setBounds(128, 267, 92, 28);
		combo_seat.setText("硬座\r\n");

		Label label_1 = new Label(composite, SWT.CENTER);
		label_1.setText("座位：");
		label_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label_1.setBounds(0, 265, 85, 30);

		Label label_price = new Label(composite, SWT.BORDER | SWT.CENTER);
		label_price.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label_price.setBounds(489, 264, 85, 30);
		label_price.setText(map1.get("p_yzprice").toString());

		Label label_1_1 = new Label(composite, SWT.CENTER);
		label_1_1.setText("余票：");
		label_1_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label_1_1.setBounds(265, 265, 85, 30);

		Label label_n = new Label(composite, SWT.BORDER | SWT.CENTER);
		label_n.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label_n.setBounds(370, 267, 77, 30);
		label_n.setText(map1.get("p_yz").toString());

		table = new Table(composite, SWT.FULL_SELECTION);
		table.setBounds(0, 46, 637, 80);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		TableColumn tblclmnNewColumn = new TableColumn(table, SWT.CENTER);
		tblclmnNewColumn.setWidth(150);
		tblclmnNewColumn.setText("列车类型");

		TableColumn tblclmnNewColumn_1 = new TableColumn(table, SWT.CENTER);
		tblclmnNewColumn_1.setWidth(85);
		tblclmnNewColumn_1.setText("列车名");

		TableColumn tblclmnNewColumn_2 = new TableColumn(table, SWT.CENTER);
		tblclmnNewColumn_2.setWidth(100);
		tblclmnNewColumn_2.setText("出发站");

		TableColumn tblclmnNewColumn_4 = new TableColumn(table, SWT.CENTER);
		tblclmnNewColumn_4.setWidth(100);
		tblclmnNewColumn_4.setText("出发时间");

		TableColumn tblclmnNewColumn_3_1 = new TableColumn(table, SWT.CENTER);
		tblclmnNewColumn_3_1.setWidth(100);
		tblclmnNewColumn_3_1.setText("终点站");

		TableColumn tableColumn = new TableColumn(table, SWT.CENTER);
		tableColumn.setWidth(100);
		tableColumn.setText("到站时间");

		table_1 = new Table(composite, SWT.FULL_SELECTION);
		table_1.setBounds(643, 46, 250, 418);
		table_1.setHeaderVisible(true);
		table_1.setLinesVisible(true);

		TableColumn tblclmnNewColumn_5 = new TableColumn(table_1, SWT.NONE);
		tblclmnNewColumn_5.setWidth(100);
		tblclmnNewColumn_5.setText("途径站点");

		TableColumn tableColumn_1 = new TableColumn(table_1, SWT.NONE);
		tableColumn_1.setWidth(70);
		tableColumn_1.setText("到站");

		TableColumn tableColumn_2 = new TableColumn(table_1, SWT.NONE);
		tableColumn_2.setWidth(70);
		tableColumn_2.setText("发车");

		Label label_1_2 = new Label(composite, SWT.CENTER);
		label_1_2.setText("出行日期：");
		label_1_2.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label_1_2.setBounds(22, 183, 100, 30);

		Label label__1 = new Label(composite, SWT.NONE);
		label__1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label__1.setBounds(128, 182, 184, 30);
		label__1.setText(date);

		//关闭按钮操作
		label_close.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				shell.dispose();
			}
		});
		//最小化操作
		label_min.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				shell.setMinimized(true);
			}
		});
		//面板拖动
		composite.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDown(MouseEvent e) {
				down = true;
				clickX = e.x;
				clickY = e.y;
			}
			@Override
			public void mouseUp(MouseEvent e) {
				down = false;
			}
		});

		composite.addMouseMoveListener(new MouseMoveListener() {
			public void mouseMove(MouseEvent e) {
				if(down) {  //down为true，说明鼠标按下，窗口跟着鼠标移动			
					shell.setLocation(shell.getLocation().x + e.x - clickX, shell.getLocation().y + e.y - clickY);
				}				
			}
		});

		//选择座位，生成票数和票价
		combo_seat.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(combo_seat.getText().equals("硬座")) {
					label_n.setText(map1.get("p_yz").toString());
					label_price.setText(map1.get("p_yzprice").toString());
				}
				if(combo_seat.getText().equals("软卧")) {
					label_n.setText(map1.get("p_rw").toString());
					label_price.setText(map1.get("p_rwprice").toString());
				}
				if(combo_seat.getText().equals("硬卧")) {
					label_n.setText(map1.get("p_yw").toString());
					label_price.setText(map1.get("p_ywprice").toString());
				}
				if(combo_seat.getText().equals("无座")) {
					label_n.setText(map1.get("p_wz").toString());
					label_price.setText(map1.get("p_wzprice").toString());
				}
			}
		});

		//点击购票，生成订单，票数减一，余额减相应的数值
		//String yname, String cname, String starttime, String endtime,String seat, String seattype, String price
		Bt_buyTicket.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				TrainDao td = new TrainDao();
				UserDao ud = new UserDao();
				String yname = combo_name.getText();//乘车人名字
				str =map.get("c_starttime").toString();
				if( map.get("c_starttime").toString().length() < 5) {//8:45
					str = "0" + map.get("c_starttime").toString(); //08:45
				}
				String starttime = date + " " + str;//发车时间
				String endtime = date + "/" + map.get("c_endtime").toString();//到站时间
				String seat = Randomseat(); //座位号
				String seattype = combo_seat.getText().trim();
				String price = null;
				String account = Values.currentLoginUser.get("u_name").toString();
				String pwd = Values.currentLoginUser.get("u_pwd").toString();
				
				//判断有无相同订单，若有，则无法继续买票
				Map<String, Object> map3 = td.findAOrder(yname, cname, starttime);
				if(map3 != null) {//说明有相同订单，则无法买票
					SWTUtil.showMessage(shell, "提示", "已有相同订单，无法继续...");
					return;
				}
				//判断选中的座位类型还有咩有余票
				if(seattype.equals("硬座") && Integer.parseInt(map1.get("p_yz").toString()) == 0) {	
					SWTUtil.showMessage(shell, "提示", "硬座余票不足，请更换座位或换一车次...");
					return;
				}
				if(seattype.equals("软卧") && Integer.parseInt(map1.get("p_rw").toString()) == 0) {
					SWTUtil.showMessage(shell, "提示", "软卧余票不足，请更换座位或换一车次...");
					return;
				}
				if(seattype.equals("硬卧") && Integer.parseInt(map1.get("p_yw").toString()) == 0) {
					SWTUtil.showMessage(shell, "提示", "硬卧余票不足，请更换座位或换一车次...");
					return;
				}
				if(seattype.equals("无座") && Integer.parseInt(map1.get("p_wz").toString()) == 0) {	
					SWTUtil.showMessage(shell, "提示", "无座余票不足，请更换座位或换一车次...");
					return;
				}
				//价格从票价表里取
				if(seattype.equals("硬座")) {		
					price = map1.get("p_yzprice").toString();
				}else if(seattype.equals("软卧")) {
					price = map1.get("p_rwprice").toString();
				}else if(seattype.equals("硬卧")) {
					price = map1.get("p_ywprice").toString();
				}else if(seattype.equals("无座")) {
					price = map1.get("p_wzprice").toString();
				}else {  //用户输入了莫名其妙的座位类型
					SWTUtil.showMessage(shell, "提示", "请选择正确的座位...");
					return;
				}

				int pricenum = Integer.valueOf(price);	//把String类型的价格转换成int类型
				//用户的余额
				int balance = Integer.valueOf(ud.findUserInfo(account, pwd).get("u_balance").toString());
				if(balance < pricenum) {//判断用户钱够不够
					SWTUtil.showMessage(shell, "提示", "余额不足，请充值 或购买更经济的座位...");
					return;
				}
				
				//生成订单
				int result = td.GenerateOrder(account, yname, cname, starttime, endtime, seat, seattype, price);

				if (result <= 0) {
					SWTUtil.showMessage(shell, "提示", "购票失败...");
					return;
				}else{
					SWTUtil.showMessage(shell, "提示", "购票成功...");
					//票数减一
					if(seattype.equals("硬座")) {		
						td.updateNumberYZ(-1, cname, date);
					}
					if(seattype.equals("软卧")) {
						td.updateNumberRW(-1, cname, date);
					}
					if(seattype.equals("硬卧")) {
						td.updateNumberYW(-1, cname, date);
					}
					if(seattype.equals("无座")) {
						td.updateNumberWZ(-1, cname, date);
					}

					//把字符串类型的price 转换成int类型，便于计算					
					int price1 = Integer.parseInt(price);
					//余额减去票价
					ud.updateBalance(-price1, account);
					shell.dispose();
				}
			}
		});


		showTrain(table);  //展示列车基本信息
		showSite(table_1);   //展示列车站点


		Label label_1_1_1 = new Label(composite, SWT.CENTER);
		label_1_1_1.setText("元");
		label_1_1_1.setFont(SWTResourceManager.getFont("Microsoft YaHei UI", 12, SWT.NORMAL));
		label_1_1_1.setBounds(580, 265, 40, 30);
	}

	//展示列车基本信息
	private void showTrain(Table table) {			
		TableItem ti = null; //行对象
		ti = new TableItem(table, SWT.NONE);
		ti.setText(new String[] {map.get("c_type").toString(), map.get("c_name").toString(), 
				map.get("c_startstation").toString(), map.get("c_starttime").toString(), 
				map.get("c_destination").toString(), map.get("c_endtime").toString()});	
	}
	//展示列车站点
	private void showSite(Table table) {
		//根据列车名字，查出列车的相关站点 存放在list中
		TrainDao trainDao = new TrainDao();
		List<Map<String, String>> list = trainDao.findSite(cname);
		//将所有站点显示到表格中
		table.removeAll(); //移除表格中原有的数据
		if(list == null || list.isEmpty()) {
			return;
		}
		TableItem ti = null; //行对象
		for(Map<String, String> mapsite : list) {
			ti = new TableItem(table, SWT.NONE);
			ti.setText(new String[] { mapsite.get("r_station"), mapsite.get("r_atime"), mapsite.get("r_stime")});
		}	
	}
	//获取当前用户的联系人  ,存入字符串数组 params中
	private void findContacts() {
		int i = 0;
		params[0] = account;
		for(Map<String, String> map2 : list) {
			String trname = map2.get("t_rname").toString();	
			++i;
			params[i] = trname;					
		}
	}


	/**
	 * 生成随机座位
	 * @return
	 */
	private String Randomseat() {
		Random rd = new Random();
		int i = rd.nextInt(20) + 1;
		int j = rd.nextInt(100) + 1;
		String str = String.valueOf(i) +"-" + String.valueOf(j);
		return str;
	}
	


}
